<template>
  <el-dialog v-model="visible" title="客户级别设置" width="800px" @close="close" :append-to-body="true">
    <el-button size="small" type="primary" :icon="Plus" @click="openForm(null)" style="margin-bottom: 5px">添加</el-button>
    <el-table :data="list" stripe border size="small" :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}" :cell-style="{textAlign: 'center'}" row-key="id">
      <el-table-column label="级别名称" prop="name"/>
      <el-table-column label="排序" prop="sort" width="120"/>
      <el-table-column label="创建时间" prop="createTime" width="150"/>
      <el-table-column label="操作" width="150">
        <template v-slot="{row}">
          <el-button size="small" type="primary" text :icon="Edit" @click="openForm(row)">编辑</el-button>
          <el-button size="small" type="danger" text :icon="Delete" @click="delLevel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="formVisible" :title="(form.id ? '编辑' : '添加') + '客户级别'" width="500px" :append-to-body="true">
      <el-form :model="form" :rules="rules" label-width="100px" size="small" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请填写名称" clearable maxlength="64"/>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="form.sort" :min="-999999" :max="999999" :controls="false"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="formVisible = false">关闭</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submit(formRef)">提交</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <el-button size="small" type="primary" @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {computed, reactive, toRefs, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Edit, Plus} from '@element-plus/icons-vue'
import levelApi from '/@/api/ums/customer/level'

export default {
  name: 'LevelSetting',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['callback', 'update:dialogVisible'],
  setup(props, context) {
    const formRef = ref()
    const {dialogVisible} = toRefs(props)
    const visible = computed({
      get: () => {
        if (dialogVisible.value) {
          getData()
        }
        return dialogVisible.value
      },
      set: val => context.emit('update:dialogVisible', val)
    })
    const state = reactive({
      form: {
        id: null,
        name: null,
        sort: 0
      },
      rules: {
        name: {required: true, message: '请填写经营范围', trigger: 'blur'}
      },
      formVisible: false,
      list: [],   // 经营范围数据
      // 添加按钮加载状态控制
      loading: false
    })

    const getData = () => levelApi.levelList().then(res => state.list = res.data).catch(e => console.log(e))
    const openForm = (item) => {
      if (item && item.id) {
        state.form = JSON.parse(JSON.stringify(item))
      } else {
        state.form = {
          id: null,
          name: null,
          sort: 0
        }
      }
      state.formVisible = true
    }
    const delLevel = (item) => {
      ElMessageBox.confirm('确定删除 ' + item.name + ' 级别？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        buttonSize: 'small',
        type: 'warning',
      }).then(() => {
        levelApi.delLevel(item).then(res => {
          if (res.data) {
            getData()
            ElMessage.success('删除成功！')
          }
        }).catch(e => console.log(e))
      }).catch(e => console.log(e))
    }
    const submit = (formEl) => {
      formEl.validate(async (valid) => {
        if (!valid) return
        state.loading = true
        let res
        try {
          if (state.form.id) {
            res = await levelApi.editLevel(state.form)
          } else {
            res = await levelApi.createLevel(state.form)
          }
          if (res.data) {
            getData()
            state.formVisible = false
            ElMessage.success('保存成功！')
          }
        } catch (e) {
          console.log(e)
        }
        state.loading = false
      })
    }
    const sizeChange = (size) => {
      state.params.current = 1
      getData()
    }
    const close = () => {
      context.emit('callback')
    }

    return {
      visible,
      close,
      formRef,
      submit,
      Edit,
      Plus,
      Delete,
      getData,
      openForm,
      delLevel,
      sizeChange,
      ...toRefs(state)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
